package SearchTree;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class SearchTreeBuilder {
	
	private SearchNode root = null;
	
	public void AddItem(String index, int offset, int length) {
		SearchNode curNode = root, preNode = null;
		for(int i=0; i<index.length(); ++i) {
			char key = index.charAt(i);
			if(curNode == null) {
				SearchNode newNode = new SearchNode(key);
				if(preNode == null){
					root = newNode;
					preNode = root;
				}
				else{
					preNode.SetChild(newNode);
					preNode = preNode.child;
				}
			} else {
				SearchNode getNode = curNode.ForceGetMatchNode(key);
				if(getNode.key < curNode.key){
					if(preNode == null){
						root = getNode;
					}
					else{
						preNode.SetChild(getNode);
					}
				}
				preNode = getNode;
			}
			curNode = preNode.child;
		}
		preNode.SetFinish(offset, length);
	}
	
	public void BuildIndex(String packageName) {
		root.Prepare();
		try {
			DataOutputStream writer = new DataOutputStream(new FileOutputStream(packageName));
			root.Export(writer);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
